package cn.com.yusys.yusp.message.service.message.channel.impl;

import java.util.Map;
import java.util.Set;

import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import cn.com.yusys.yusp.commons.config.ApplicationProperties;
import cn.com.yusys.yusp.message.service.message.channel.EmailSendInterface;
@Service("DefaultEmailSendImpl")
public class DefaultEmailSendImpl implements EmailSendInterface{
	@Autowired
	private ApplicationProperties applicationProperties;
	
	@Autowired
    private JavaMailSender mailSender;
	
	private Logger logger = LoggerFactory.getLogger(DefaultEmailSendImpl.class);

	
	@Override
	public int sendMessage(String toEmail, String title, String content, Map<String,byte[]> attachments) {
		try {
			long time = System.currentTimeMillis();
			MimeMessage mimeMessage = mailSender.createMimeMessage();
			MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

			helper.setFrom(applicationProperties.getEmail().getUsername());// 发送者.
			helper.setTo(toEmail);// 接收者.
			helper.setSubject(title);// 邮件主题.
			helper.setText(content,true);// 邮件内容.
			if(null!=attachments&&!attachments.isEmpty()){
				Set<String> keys = attachments.keySet();
				for(String attachmentName:keys){
					ByteArrayResource byteArrayResource = new ByteArrayResource(attachments.get(attachmentName));
					helper.addAttachment(attachmentName, byteArrayResource);
				}				
			}			
			mailSender.send(mimeMessage);
			logger.info("Send to: "+toEmail+" Mail time consuming:"+(System.currentTimeMillis()-time)+"ms");
			return 0;
		} catch (Exception e) {
			logger.error("Failed to send mail "+e.getMessage());
		}
		return 1;
	}

}
